package com.example.dirviesystem.coach.service;

import com.example.dirviesystem.coach.dto.DrivingProgressDTO;
import com.example.dirviesystem.entity.DrivingProgress;
import com.example.dirviesystem.repository.DrivingProgressRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DrivingProgressService {

    private final DrivingProgressRepository progressRepository;

    public List<DrivingProgressDTO> getAllProgress(String name, Pageable pageable) {
        Page<DrivingProgress> page;
        if (StringUtils.hasText(name)) {
            page = progressRepository.findByStudentNameContaining(name, pageable);
        } else {
            page = progressRepository.findAll(pageable);
        }
        return page.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public DrivingProgressDTO updateProgress(DrivingProgressDTO dto) {
        DrivingProgress progress = progressRepository.findById(dto.getId())
                .orElseThrow(() -> new RuntimeException("Progress not found"));

        progress.setSubjectOnePassed(dto.isSubjectOnePassed());
        progress.setSubjectTwoPassed(dto.isSubjectTwoPassed());
        progress.setSubjectThreePassed(dto.isSubjectThreePassed());
        progress.setSubjectFourPassed(dto.isSubjectFourPassed());
        progress.setComments(dto.getComments());

        DrivingProgress saved = progressRepository.save(progress);
        return convertToDTO(saved);
    }

    private DrivingProgressDTO convertToDTO(DrivingProgress progress) {
        DrivingProgressDTO dto = new DrivingProgressDTO();
        dto.setId(progress.getId());
        dto.setStudentId(progress.getStudent().getId());
        dto.setStudentName(progress.getStudent().getName());
        dto.setSubjectOnePassed(progress.isSubjectOnePassed());
        dto.setSubjectTwoPassed(progress.isSubjectTwoPassed());
        dto.setSubjectThreePassed(progress.isSubjectThreePassed());
        dto.setSubjectFourPassed(progress.isSubjectFourPassed());
        dto.setComments(progress.getComments());
        return dto;
    }
}